/**
 * 
 */
package com.hs.core.db;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletContext;
import javax.sql.DataSource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.hs.core.model.BlobObj;
import com.hs.core.model.TextObj;
import com.hs.core.utils.SystemUtil;

 

/**
 * @author shl
 *
 */
public class DBMgr {
	private static final Logger logger = Logger.getLogger(DBMgr.class);
	
	private static DataSource dboDataSource = null;
	private XmlBeanFactory factory = null;
	private JdbcTemplate jdbcTemplate ;
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		logger.debug("============"+SystemUtil.getClassLoaderRoot().getAbsolutePath());
		List l = DBMgr.getDbUtilInst().queryList("select * from ps_patent_basicinfo", null);
		logger.debug("1111:" + l.size());
	}
	
	private static  DBMgr _instance = null;
	
	private DBMgr(){
		if(dboDataSource == null){
			String resPath = "";
			try {
				resPath = SystemUtil.getClassLoaderRoot().getAbsolutePath() + "/dbContext.xml";
			} catch (Exception e) {
				 logger.debug("异常信息:" + e.getStackTrace());
			}
			
			FileSystemResource res = new FileSystemResource(resPath);
			factory = new XmlBeanFactory(res);
			dboDataSource = (DataSource)factory.getBean("dataSource");
			setDataSource(dboDataSource); 
			jdbcTemplate = (JdbcTemplate)factory.getBean("jdbcTemplate");
			 
			
		}
	}
	private DBMgr(ServletContext context){
		try {
			init(context);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 获取数据库管理实例
	 * @return
	 */
	public static DBMgr getDbUtilInst(ServletContext context){
		if(null == _instance){
			_instance = new DBMgr(context);
		}  
		return _instance;
	}
	/**
	 * 获取数据库管理实例
	 * @return
	 */
	public static DBMgr getDbUtilInst(){
		if(null == _instance){
			_instance = new DBMgr();
		}   
		return _instance;
	}
	
	public void init(ServletContext context){
		if(dboDataSource == null){
			WebApplicationContext wac = WebApplicationContextUtils
													.getRequiredWebApplicationContext(context);
			setDataSource((DataSource)wac.getBean("dataSource"));
		} 
	}
	public void setDataSource(DataSource dataSource) {
		dboDataSource = dataSource;
	}
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	/**
	 * 获取数据库链接
	 * @return
	 */
	public Connection getConnection(){
		
		try { 
			return jdbcTemplate.getDataSource().getConnection();
		} catch (SQLException e) { 
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 
	 * 功能: (回调)从数据库取出一个BLob对象，要求sql的？和params的内容对应
	 * 作者: Lihuiming
	 * 创建日期:2007-4-7
	 * @param sql
	 * @param params
	 * @return BlobObj是包含blob数据的对象，data是byte数组
	 */
	public BlobObj getBlob(String sql, Object[] params){
		if(sql == null || sql.length() == 0 )
			return new BlobObj();
		
		jdbcTemplate = new JdbcTemplate(dboDataSource);
		if(this.queryList(sql, params).size()==0)
			return new BlobObj();
		RowMapper mapper = new RowMapper(){
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				BlobObj blobObj = new BlobObj();
				
				InputStream is = rs.getBlob(1).getBinaryStream();
				
				try {
					byte[] data = new byte[1024];
					String filePath = "";
					try {
						filePath = SystemUtil.getWebappRoot().getAbsolutePath();
					} catch (Exception e) {
						logger.debug("找不到路径" + e.getStackTrace());
					}
					
//					String fileStr = InitSystem.getBpmParam(Constants.PROJECT_ABS_PATH)+"/temp/"+"tempfile.txt";
					String fileStr = filePath +"/temp/"+"tempfile.txt";;
					File file = new File(fileStr); 
					FileOutputStream fos = new FileOutputStream(file);
					int len = 0;
					while((len = is.read(data)) != -1){
						fos.write(data, 0, len);
						
					}
					fos.close();
					FileInputStream fis = new FileInputStream(file);
					
					byte[] data2 = new byte[fis.available()];
					fis.read(data2);
					
					fis.close();
					file.delete();
					blobObj.setData(data2);
				} catch (IOException e) {
					e.printStackTrace();
				} 
				return blobObj;
			}
		};
		
		Object blob = jdbcTemplate.queryForObject(sql, params,mapper);
		
		return (BlobObj)blob;
	}
	 
	/**
	 * 
	 * 功能: (回调)从数据库取出一个CLob对象，要求sql的？和params的内容对应
	 * 作者: shiliang
	 * 创建日期:2007-4-7
	 * @param sql
	 * @param params
	 * @return TextObj是包含blob数据的对象，data是byte数组
	 */
	public TextObj getClob(String sql, Object[] params){
		if(sql == null || sql.length() == 0 )
			return new TextObj();
		
		jdbcTemplate = new JdbcTemplate(dboDataSource);
		
		RowMapper mapper = new RowMapper(){
			public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
				TextObj clobObj = new TextObj();
				
				try {
					clobObj.setData(new String(rs.getBytes(1),"utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				
				return clobObj;
			}
		};
		Object blob = jdbcTemplate.queryForObject(sql, params,mapper);
		
		return (TextObj)blob;
	}
	/**
	 * 
	 * 功能: 执行sql查询，list的每个元素是一行（Map）
	 * 作者: shiliang
	 * 创建日期:2007-4-4
	 * @param sql    查询sql
	 * @param params 参数
	 * @return
	 */
	public List queryList(String sql , Object[] params){	
		jdbcTemplate = new JdbcTemplate(dboDataSource);
		
		//logger.info("SQL=="+sql+" params="+params);
		List list = jdbcTemplate.queryForList(sql,params); 
		return list;
	}
	/**
	 * 查询INT型数据
	 * @param sql
	 * @param params
	 * @return
	 */
	public int queryCountForInt(String sql , Object[] params){
		jdbcTemplate = new JdbcTemplate(dboDataSource);
		
		return jdbcTemplate.queryForInt(sql, params);
	}
	/**
	 * 查询Long型数据
	 * @param sql
	 * @param params
	 * @return
	 */
	public long queryCountForLong(String sql , Object[] params){
		jdbcTemplate = new JdbcTemplate(dboDataSource);
		
		return jdbcTemplate.queryForLong(sql, params);
	}
	public Object getBigObject(){
		
		return null;
	}
	
	/**
	 * 
	 * 功能: 增删改数据，主要处理大对象blob，clob
	 * 作者: shiliang
	 * 创建日期:2007-4-6
	 * @param sql
	 * @param data
	 * @return -1表示失败，0表示没有更新，大于0表示更新数据
	 */
	public int update(String sql , Object[] data){
		if(sql == null || sql.length() == 0 )
			return -1; 
		int result = 0;
		jdbcTemplate = new JdbcTemplate(dboDataSource);
		result = jdbcTemplate.update(sql, data);
		 
		return result;
	}
	/**
	 * 
	 * 功能: 批量执行sql
	 * 作者: shiliang
	 * 创建日期:2011-09-16
	 * @param sql
	 * @param data
	 * @return -1表示失败，0表示没有更新，大于0表示更新数据
	 */
	public int[] batchUpdateBysql(String[] sql){
		if(sql == null || sql.length == 0 )
			return null; 
		int[] result = null;
		jdbcTemplate = new JdbcTemplate(dboDataSource);
		result = jdbcTemplate.batchUpdate(sql);
		 
		return result;
	}
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

}
